//
//  BindingController.swift
//  Alamofire
//
//  Created by 易先生 on 2022/9/9.
//

import UIKit
import RxCocoa
import RxSwift
import MYModule
import CRPSmartRing
import SDWebImage
import SwiftUI
import CoreLocation
import CoreBluetooth

class BindingController: ViewController {

	private lazy var viewModel = BindingViewModel()
    
    private(set) var indexPath: IndexPath?
    
    fileprivate var hud: HUD?

	override func viewDidLoad() {
		super.viewDidLoad()
        
        didScaning()
	}
    
   
	override func makeUI() {
		super.makeUI()

        self.view.backgroundColor =  UIColor.darkBackground

        self.view.addSubview(headTitleView)
		headTitleView.snp.makeConstraints { make in
			make.top.equalTo(self.topLayoutGuide.snp.bottom)
			make.leading.equalToSuperview()
			make.trailing.equalToSuperview()
		}
        

        self.view.addSubview(self.subtitle)
        self.subtitle.snp.makeConstraints { make in
            make.top.equalTo(self.headTitleView.snp.bottom).offset(-24.5)
            make.leading.equalTo(20)
            make.trailing.equalTo(-20)
            make.centerX.equalToSuperview()
        }
        self.view.addSubview(tableView)
		tableView.snp.makeConstraints { make in
            make.top.equalTo(subtitle.snp.bottom).offset(13)
			make.leading.trailing.bottom.equalToSuperview()
		}

        self.view.addSubview(deviceFindView)
		deviceFindView.snp.makeConstraints { make in
			make.edges.equalToSuperview()
		}
	}
    
    override func backAction() {
        self.viewModel.interruptScan()
        super.backAction()
    }
    
    func didScaning() {
        
        if BluetoothManager.shared.bluetoothState != .poweredOn {
            self.deviceFindView.isHidden = false
            showAlertController()
            return
        }
        self.startScanIfTurnOnLocation()
    }
    
    func startScanIfTurnOnLocation() {
        
        LocationManager.shared.authLocationPermission {
            self.viewModel.clean()
            self.deviceFindView.isHidden = true
            self.showFootView(isShow: false)
            self.viewModel.scan()
        } closed: {
            self.deviceFindView.isHidden = false
            self.showFootView(isShow: true)
            
            self.viewModel.clean()
        } cancel: {
            self.backAction()
        }
    }

	override func bindViewModel() {
		super.bindViewModel()
		deviceFindView.helpButton.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
			let vc = BindHelpController()
			self.navigationController?.pushViewController(vc, animated: true)
		}.disposed(by: rx.disposeBag)

		deviceFindView.retryButton.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
            
			self.showFootView(isShow: false)
            
            self.didScaning()
			
		}.disposed(by: rx.disposeBag)

		viewModel.devicesRelay.bind(to: tableView.rx.items(cellIdentifier: BindingCell.reuseIdentifier, cellType: BindingCell.self)) { _, element, cell in
			cell.bind(to: element)
		}.disposed(by: rx.disposeBag)

		viewModel.finishScanRelay.subscribe(onNext: { [weak self] discoverys in
			guard let self = self else { return }
			if discoverys.count > 0 {
				self.showFootView(isShow: true)
				self.deviceFindView.isHidden = true
			} else {
				self.deviceFindView.isHidden = false
			}
		}).disposed(by: rx.disposeBag)


        NotificationCenter.default.rx
            .notification(.kUpdateUINotification)
            .take(until: rx.deallocated)
            .subscribe(onNext: { [weak self] notification in
                
                guard let dict = notification.userInfo as? [String: Any], let type = dict["type"] as? NotifactionType else { return }
                
                switch type {
                case .deviceState:
                    
                   
                    guard let state = dict["result"] as? CRPSmartRing.CRPState else { return }
                    /// 已连接上 退出
                    if state == .connected {
                        
                        if let indexPath = self?.indexPath, let model = self?.viewModel.models[indexPath.row] {
                            self?.viewModel.saveDeviceInfo(model)
                        }
                        
                        self?.hud?.dismiss(animated: true)
                        
                        self?.backAction()
                        
                    }
                    
                    break
                case .bluetoothState:
                    /// 开关蓝牙都清理
                    if BluetoothManager.shared.bluetoothState == .poweredOff {
                        self?.viewModel.clean()
                    } else if BluetoothManager.shared.bluetoothState == .poweredOn {
                        
                        self?.didScaning()
                    }
                    
                    break
                default:
                    break
                }
		}).disposed(by: rx.disposeBag)

		tableView.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in
			guard let self = self else { return }
            
            let hud = HUD()
            self.present(hud, animated: true)
            self.hud = hud
            
			self.viewModel.interruptScan()
            self.viewModel.remove()
            self.indexPath = indexPath
            let model = self.viewModel.models[indexPath.row]
            self.viewModel.connect(model)
            self.viewModel.saveDeviceInfo(model)
			
		}).disposed(by: rx.disposeBag)
        
        NotificationCenter.default.rx.notification(.kReceiveLocationPermissionNotification).take(until: self.rx.deallocated).subscribe(onNext: { [weak self] notification in
            guard let self = self else { return }
            self.startScanIfTurnOnLocation()
        }).disposed(by: rx.disposeBag)
	}


	private func showFootView(isShow: Bool = true) {
		footView.isHidden = isShow
		guard isShow else {
			footView.startAnimating()
			return
		}
		footView.stopAnimating()
	}

	private func showAlertController() {
		let alertController = UIAlertController(title: "ble_disable".language,
			message: "dialog_device_bound_ble_disable_location".language,
			preferredStyle: UIAlertController.Style.alert)
        let okAction = UIAlertAction(title: "dialog_confirm".language, style: UIAlertAction.Style.default, handler: {_ in
            // 去蓝牙设置页面
            self.toBloothSetting()
        })
                                     
		alertController.addAction(okAction)
		self.present(alertController, animated: true, completion: nil)
	}

	private lazy var deviceFindView: NotDeviceFindView = {
		let deviceFindView = NotDeviceFindView()
		deviceFindView.backgroundColor = .white
		deviceFindView.isHidden = true
		return deviceFindView
	}()

	private lazy var headTitleView: TopTitleView = {
		let headTitleView = TopTitleView()
        headTitleView.configTitle(title: "device_add_btn_title".language, detail: "device_tip_bind_content".language)
        headTitleView.detailLabel.isHidden = true
		return headTitleView
	}()
    
    private lazy var gifImageView: ImageView = {
        let view = ImageView()
        view.backgroundColor = .white
        view.contentMode = .scaleAspectFit
        view.setFastCorners(20)
        let path = Bundle.main.path(forResource: "charging", ofType: "gif")
        let url = URL(fileURLWithPath: path!)
        view.sd_setImage(with: url)
        return view
    }()
    
    private lazy var subtitle: MYModule.Label = {
        let label = Label()
        label.numberOfLines = 0
        label.font = Fonts.boldSystemFont(ofSize: 18)
        label.textColor = UIColor.assist_222222
        label.text = "device_tip_bind_list_title".language
        return label
    }()

	private lazy var tableView: UITableView = {
		let tableView = UITableView(frame: .zero, style: .plain)
		tableView.separatorColor = UIColor.assist_222222
		tableView.backgroundColor = .clear
        tableView.rowHeight = UITableView.automaticDimension
		tableView.sectionFooterHeight = 0
		tableView.sectionHeaderHeight = 0
		tableView.register(BindingCell.self, forCellReuseIdentifier: BindingCell.reuseIdentifier)
		tableView.tableFooterView = footView
        tableView.separatorColor = UIColor.assist_D0D0D0
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
		return tableView
	}()

	private lazy var footView: BindFootView = {
		let footView = BindFootView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44))
		footView.configHit(hit: "binding_searching".language)
		footView.isHidden = true
		return footView
	}()
}

extension BindingController {
    
    func toBloothSetting() {
        
        let url =  URL(string: "App-Prefs:root=Bluetooth")!
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)

        } else {
            UIApplication.shared.open(url)
        }
    }
}
